package itsm.isperp.framework.web.request;

import itsm.isperp.framework.data.ObjectSqlSource;
import itsm.isperp.framework.data.domain.FilterRule;
import itsm.isperp.framework.data.domain.QueryFilter;
import itsm.isperp.framework.utils.JsonBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * jqGrid 数据请求 {@link JqGridRequest} 过滤器。 <br/>
 * 一个jqGrid过滤器格式如下：
 * 
 * <pre>
 * {"groupOp":"AND","rules":[{"field":"firstName","op":"eq","data":"John"}]}
 * </pre>
 * <p>
 * groupOp：“and”表示与，为“or”表示或。Rules中的field表示条件的依据名称。
 * </p>
 * <p>
 * op({@link JqGridFilterRuleOp})
 * ：表示条件（eq=等于，ne=不等，lt=小于，le=小于等于，gt=大于，ge=大于等于，bw=开始于，bn=不开始于，in=在，ni=不在内，
 * ew=结束于，en=不结束于，cn=包含，nc=不包含）。
 * </p>
 * <p>
 * data：表示的条件值。
 * </p>
 * 
 * @author lizx
 * @date 2013-1-24
 * @version V1.0
 */
public class JqGridFilter implements Serializable, ObjectSqlSource, QueryFilter {

	/**
	 * 
	 */
	private static final long serialVersionUID = -122991403041266824L;

	private String source;

	private String groupOp;

	private List<JqGridFilterRule> rules;

	public JqGridFilter() {
		groupOp = QueryFilter.DEFAULT_OP;
	}

	@JsonIgnore
	@Override
	public String getSql() {
		StringBuilder sb = new StringBuilder();
		if (rules != null) {
			for (JqGridFilterRule rule : rules) {
				if (StringUtils.isNotEmpty(rule.getField()))
					sb.append(" ").append(this.groupOp).append(" ")
							.append(rule.getSql());
			}

		} else {
			sb.append(" AND (1=1) ");
		}
		return sb.toString();
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getGroupOp() {
		return groupOp;
	}

	public void setGroupOp(String groupOp) {
		this.groupOp = groupOp;
	}

	public List<JqGridFilterRule> getRules() {
		return rules;
	}

	public void setRules(List<JqGridFilterRule> rules) {
		this.rules = rules;
	}

	@Override
	public String toString() {

		return JsonBuilder.buildNormalBinder().toJson(this);
	}

	/**
	 * 抛出UnsupportedOperationException 异常
	 */
	@JsonIgnore
	@Override
	public Pageable getPageable() {
		return null;
	}

	@Override
	public void addRule(FilterRule rule) {
		if (this.rules == null)
			this.rules = new ArrayList<JqGridFilterRule>();
		if (rule != null)
			this.rules.add((JqGridFilterRule) rule);
	}

	@Override
	public void addRule(String field, JqGridFilterRuleOp op, String data) {
		if (this.rules == null)
			this.rules = new ArrayList<JqGridFilterRule>();

		this.rules.add(new JqGridFilterRule(field, op, data));
	}
}
